#!/usr/bin/env python
#
# Copyright 2015 Time-My-Life team (NSC 2015).
#
import webapp2
import json
import logging
from dbase import *


class UpdateHandler(webapp2.RequestHandler):
    def get(self):
        ''' Update latest status of smartphone usage '''
        try:
            # 1. extract 'id' parameter as integer
            id = int(self.request.get('id'))
            # 2. query for corresponding Account
            account_query = Account.query(Account.id==id)
            accounts = account_query.fetch(1)
            if  len(accounts) > 0:               
                id_key = accounts[0].key
                # 3. extract values from POST request
                dow = int(self.request.get('dow'))
                param = self.request.get('values')
                values = [int(x) for x in param.split(',')]
                # 4. create DataObject with <id> as parent, then put into Datastore
                new_data = DataObject(parent=id_key, day_of_week = dow,values=values)
                new_data.put()
                # 5. create JSON response with 'OK' status
                resp = {'status':'OK'}
                logging.info('Update %d with %s'%(id,param))
            else:
                logging.debug('Unknown ID')
                resp = {'status':'ERROR'}
        except:
            # 6. create JSON response with 'ERROR' status
            resp = {'status':'ERROR'}
            
            logging.debug('Wrong ID parameter')
        self.response.write(json.dumps(resp))

app = webapp2.WSGIApplication([
    ('/update', UpdateHandler)
], debug=True)